package cn.gdchent.springbootsecurity.authentication;
import cn.gdchent.springbootsecurity.utils.JwtTokenUtil;
import cn.gdchent.springbootsecurity.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 拦截器 会在控制器之前调用
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {


    @Autowired
    private UserDetailsService userDetailsService ;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        System.out.println("JwtAuthenticationTokenFilter_doFilterInternal调用");
        String jwtToken=request.getHeader("Authorization"); //获取客户端的请求token
        if(jwtToken!=null&& StringUtils.isNotEmpty(jwtToken)){
              //通过token 获取用户名
            String username=jwtTokenUtil.getUsernameFromToken(jwtToken);
            if(username!=null&& SecurityContextHolder.getContext().getAuthentication()==null){
                 UserDetails userDetails =userDetailsService.loadUserByUsername(username);
                 if(jwtTokenUtil.validateToken(jwtToken,userDetails)){
                      //使用jwt令牌进行授权
                     UsernamePasswordAuthenticationToken authenticationToken=new
                             UsernamePasswordAuthenticationToken(
                                     userDetails,null,
                                     userDetails.getAuthorities()
                     );
                     SecurityContextHolder.getContext().setAuthentication(authenticationToken);
                 }
            }
        }
        filterChain.doFilter(request,response);
    }
}
